package perfect.tool.validator;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.Set;

import org.dom4j.Attribute;
import org.dom4j.Element;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.HBox;
import javafx.stage.WindowEvent;
import perfect.tool.log.ListViewAppender;
import perfect.tool.log.Log;
import perfect.tool.xml.Utils;
import perfect.tool.xml.XmlManager;

public class ValidatorController extends HBox implements Initializable {

	@FXML
	Button saveXml;
	
	@FXML
	TreeView<String> treeViewList;
	@FXML
	TreeView<String> treeViewProtocol;

	@FXML
	ContextMenu contextMenuList;
	@FXML
	ContextMenu contextMenuProtocol;
	@FXML
	ListView<String> listViewAppender;
	
	@FXML
	MenuItem miLAdd;
	@FXML
	MenuItem miLDelete;
	
	@FXML
	Button btnUp;
	@FXML
	Button btnDown;

	@FXML
	MenuItem miByte;
	@FXML
	MenuItem miShort;
	@FXML
	MenuItem miInt;
	@FXML
	MenuItem miDword;
	@FXML
	MenuItem miString;

	@FXML
	MenuItem miIf;
	@FXML
	MenuItem miElseIf;
	@FXML
	MenuItem miFor;
	@FXML
	MenuItem miMin;
	@FXML
	MenuItem miMax;
	@FXML
	MenuItem miDelTag;

	@FXML
	MenuItem miAmend;

	private Map<String, Set<String>> tableTagToMenuItem = new HashMap<>();

	public ValidatorController() {
		super();

		FXMLLoader loader = new FXMLLoader(ValidatorController.class.getResource("Main.fxml"));
		loader.setRoot(this);
		loader.setController(this);

		try {
			loader.load();
		} catch (IOException e) {
			e.printStackTrace();
		}

		Log.addAppender(new ListViewAppender(listViewAppender));
		
		Log.info("编辑器启动！");
		
		System.out.println("ValidatorController Initializable");
	}
	
	public void onCloseRequest(WindowEvent event) {
		Alert exitAlert = new Alert(AlertType.WARNING);
		exitAlert.setTitle("退出前记得保存哦！！！");
		exitAlert.setHeaderText("是否退出程序？退出前不要忘记保存哦？(*^▽^*)");
		exitAlert.setContentText("点击“是”将立刻关闭应用程序，点击“否”将取消操作。");
		
		ButtonType buttonTypeSave = new ButtonType("保存并退出");
		ButtonType buttonTypeYes = new ButtonType("直接退出");
		ButtonType buttonTypeNO = new ButtonType("取消");
		exitAlert.getButtonTypes().setAll(buttonTypeSave, buttonTypeYes, buttonTypeNO);
		
		Optional<ButtonType> result = exitAlert.showAndWait();
		if (result.get() == buttonTypeNO) {
			// 阻止窗口关闭
			event.consume();
		} else if (result.get() == buttonTypeSave) {
			XmlManager.getMe().saveXml();
		}
	}
	

	@SuppressWarnings("unchecked")
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		menuItemTableInit();
		
		menuItemActionInit();
		
		saveXml.setOnAction(event->{
			XmlManager.getMe().saveXml();
		});
		
		{
			treeViewList.setShowRoot(false);
			treeViewProtocol.setShowRoot(false);
			
			// 载入配置文件
			XmlManager.getMe().load();
			
			Element elementProtocols = XmlManager.getMe().getElementProtocols();
			
			RootProtocolTreeItem rootItem = new RootProtocolTreeItem(elementProtocols);
			treeViewList.setRoot(rootItem);

			treeViewList.setOnContextMenuRequested(event -> {
				// contextMenuList.show(this, event.getScreenX(), event.getScreenY());
			});

			treeViewProtocol.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
			// 显示协议详细数据
			treeViewList.setOnMouseClicked(event -> {
				TreeItem<String> selectedTreeItem = treeViewList.getSelectionModel().getSelectedItem();
				if (selectedTreeItem instanceof ProtocolTreeItem) {
					ProtocolTreeItem selectProtocolTreeItem = (ProtocolTreeItem) selectedTreeItem;
					
					Element elementProtocol = selectProtocolTreeItem.getElement();
					
					int protocolId = selectProtocolTreeItem.getProtocolId();
					
					RootNodeTreeItem rootNodeTreeItem = new RootNodeTreeItem(protocolId, elementProtocol);
					rootNodeTreeItem.expandAll();
					treeViewProtocol.setRoot(rootNodeTreeItem);
				}
			});

			// 显示右键菜单
			treeViewProtocol.setOnContextMenuRequested(event -> {
				TreeItem<String> selectedTreeItem = treeViewProtocol.getSelectionModel().getSelectedItem();

				for (MenuItem menuItem : contextMenuProtocol.getItems()) {
					menuItem.setVisible(false);
				}

				if (selectedTreeItem instanceof NodeTreeItem) {
					NodeTreeItem nodeTreeItem = (NodeTreeItem) selectedTreeItem;

					Set<String> menuItemIds = tableTagToMenuItem.getOrDefault(nodeTreeItem.getNodeName(),
							new HashSet<>());

					for (MenuItem menuItem : contextMenuProtocol.getItems()) {
						if (menuItemIds.contains(menuItem.getId())) {
							menuItem.setVisible(true);
						}
					}
				}
			});

			treeViewList.getSelectionModel().selectionModeProperty().addListener(event -> {
				//btnUp.setDisable(true);
				//btnDown.setDisable(true);
			});
			
//			treeViewProtocol.getSelectionModel().selectionModeProperty().addListener(event -> {
//				btnUp.setDisable(true);
//				btnDown.setDisable(true);
//				
//				TreeItem<String> treeItem = treeViewProtocol.getSelectionModel().getSelectedItem();
//				if (treeItem instanceof NodeTreeItem) {
//					NodeTreeItem nodeTreeItem = (NodeTreeItem)treeItem;
//					String nodeName = nodeTreeItem.getNodeName();
//					if (nodeName.equals("BYTE") 
//							|| nodeName.equals("SHORT") 
//							|| nodeName.equals("INT")
//							|| nodeName.equals("DWORD")
//							|| nodeName.equals("STRING")) {
//						btnUp.setDisable(false);
//						btnDown.setDisable(false);
//					}
//				}
//			});
			
			btnUp.setOnAction(event->{
				TreeItem<String> treeItem = treeViewProtocol.getSelectionModel().getSelectedItem();
				if (treeItem instanceof NodeTreeItem) {
					NodeTreeItem currNodeTreeItem = (NodeTreeItem)treeItem;
					String nodeName = currNodeTreeItem.getNodeName();
					if (nodeName.equals("BYTE") 
							|| nodeName.equals("SHORT") 
							|| nodeName.equals("INT")
							|| nodeName.equals("DWORD")
							|| nodeName.equals("STRING")) {
						// 标签上移
						TreeItem<String> parentTreeItem = currNodeTreeItem.getParent();
						if (parentTreeItem instanceof NodeTreeItem) {
							Element currElement = currNodeTreeItem.getElement();
							
							NodeTreeItem parentNodeTreeItem = (NodeTreeItem)parentTreeItem;
							
							// 获取上一个NodeTreeView
							int currNodeIndex = parentNodeTreeItem.getChildren().indexOf(currNodeTreeItem);
							if (currNodeIndex <= 0) {
								// 已经在最前面，不用移动
								return ;
							}
							
							// 获取前面的节点
							TreeItem<String> prevTreeItem = parentNodeTreeItem.getChildren().get(currNodeIndex - 1);
							if (!(prevTreeItem instanceof NodeTreeItem)) {
								return ;
							}
							
							NodeTreeItem prevNodeTreeItem = (NodeTreeItem)prevTreeItem;
							Element prevElement = prevNodeTreeItem.getElement();
							
							Element parentElement = parentNodeTreeItem.getElement();
							List<Element> elements = parentElement.elements();
							int prevIndex = elements.indexOf(prevElement);
							int currIndex = elements.indexOf(currElement);
							elements.remove(prevElement);
							elements.remove(currElement);
							
							// 换顺序
							elements.add(prevIndex, currElement);
							elements.add(currIndex, prevElement);
							
							parentNodeTreeItem.getChildren().clear();
							parentNodeTreeItem.createChildren();
							
							// 选中标签
							TreeItem<String> selectedTreeItem = parentNodeTreeItem.getChildren().get(currNodeIndex - 1);
							treeViewProtocol.getSelectionModel().select(selectedTreeItem);
						}
					}
				}
			});
			
			btnDown.setOnAction(event->{
				TreeItem<String> treeItem = treeViewProtocol.getSelectionModel().getSelectedItem();
				if (treeItem instanceof NodeTreeItem) {
					NodeTreeItem currNodeTreeItem = (NodeTreeItem)treeItem;
					String nodeName = currNodeTreeItem.getNodeName();
					if (nodeName.equals("BYTE") 
							|| nodeName.equals("SHORT") 
							|| nodeName.equals("INT")
							|| nodeName.equals("DWORD")
							|| nodeName.equals("STRING")) {
						// 标签上移
						TreeItem<String> parentTreeItem = currNodeTreeItem.getParent();
						if (parentTreeItem instanceof NodeTreeItem) {
							Element currElement = currNodeTreeItem.getElement();
							
							NodeTreeItem parentNodeTreeItem = (NodeTreeItem)parentTreeItem;
							
							// 获取上一个NodeTreeView
							int currNodeIndex = parentNodeTreeItem.getChildren().indexOf(currNodeTreeItem);
							if (currNodeIndex >= parentNodeTreeItem.getChildren().size()-1) {
								// 已经在最后面了，不用移动
								return ;
							}
							
							// 获取前面的节点
							TreeItem<String> nextTreeItem = parentNodeTreeItem.getChildren().get(currNodeIndex + 1);
							if (!(nextTreeItem instanceof NodeTreeItem)) {
								return ;
							}
							
							NodeTreeItem nextNodeTreeItem = (NodeTreeItem)nextTreeItem;
							Element nextElement = nextNodeTreeItem.getElement();
							
							Element parentElement = parentNodeTreeItem.getElement();
							List<Element> elements = parentElement.elements();
							int currIndex = elements.indexOf(currElement);
							int nextIndex = elements.indexOf(nextElement);
							elements.remove(currElement);
							elements.remove(nextElement);
							
							// 换顺序
							elements.add(currIndex, nextElement);
							elements.add(nextIndex, currElement);
							
							parentNodeTreeItem.getChildren().clear();
							parentNodeTreeItem.createChildren();
							
							// 选中标签
							TreeItem<String> selectedTreeItem = parentNodeTreeItem.getChildren().get(currNodeIndex + 1);
							treeViewProtocol.getSelectionModel().select(selectedTreeItem);
						}
					}
				}
			});
			
		}

	}

	private void menuItemActionInit() {
		miLAdd.setOnAction(event -> {
			TreeItem<String> rootTreeItem = treeViewList.getRoot();
			if (rootTreeItem instanceof RootProtocolTreeItem) {
				RootProtocolTreeItem rootProtocolTreeItem = (RootProtocolTreeItem)rootTreeItem;
				rootProtocolTreeItem.addProtocol();
			}
		});
		
		miLDelete.setOnAction(event -> {
			TreeItem<String> selectedTreeItem = treeViewList.getSelectionModel().getSelectedItem();
			if (null == selectedTreeItem) {
				return ;
			}
			
			if (selectedTreeItem instanceof ProtocolTreeItem) {
				ProtocolTreeItem protocolTreeItem = (ProtocolTreeItem)selectedTreeItem;
				protocolTreeItem.deleteSelf();
			}
		});
		
		//miByte.setAccelerator(KeyCombination.keyCombination("I"));
		miByte.setOnAction(event -> {
			addTreeViewNode("BYTE");
		});
		
		miShort.setOnAction(event -> {
			addTreeViewNode("SHORT");
		});
		
		miInt.setOnAction(event -> {
			addTreeViewNode("INT");
		});
		
		miDword.setOnAction(event -> {
			addTreeViewNode("DWORD");
		});
		
		miString.setOnAction(event -> {
			addTreeViewNode("STRING");
		});
		
		miIf.setOnAction(event -> {
			addTreeViewNode("IF");
		});
		
		miElseIf.setOnAction(event -> {
			
			addTreeViewNode("ELSEIF");
		});
		
		miFor.setOnAction(event -> {
			addTreeViewNode("FOR");
		});
		
		miMin.setOnAction(event -> {
			addTreeViewNode("MIN");
		});
		
		miMax.setOnAction(event -> {
			addTreeViewNode("MAX");
		});
		
		miDelTag.setOnAction(event -> {
			TreeItem<String> selectedTreeItem = treeViewProtocol.getSelectionModel().getSelectedItem();
			if (null == selectedTreeItem) {
				Log.error("没有选中的节点.null == selectedTreeItem");
				return ;
			}
			
			if (!(selectedTreeItem instanceof NodeTreeItem)) {
				Log.error("!(selectedTreeItem instanceof NodeTreeItem)");
				return ;
			}
			
			NodeTreeItem nodeTreeItem = (NodeTreeItem) selectedTreeItem;
			
			nodeTreeItem.removeSelf();
		});
		
		miAmend.setOnAction(event -> {
			TreeItem<String> selectedTreeItem = treeViewProtocol.getSelectionModel().getSelectedItem();
			if (null == selectedTreeItem) {
				Log.error("没有选中的节点.null == selectedTreeItem");
				return ;
			}
			
			if (!(selectedTreeItem instanceof NodeTreeItem)) {
				Log.error("!(selectedTreeItem instanceof NodeTreeItem)");
				return ;
			}
			
			NodeTreeItem nodeTreeItem = (NodeTreeItem) selectedTreeItem;
			
			// 修改数据
			nodeTreeItem.amendText();
		});
	}

	private void menuItemTableInit() {
		// ID
		{
			Set<String> menuItemNames = new HashSet<>();
			menuItemNames.add("miAmend");

			tableTagToMenuItem.put("ID", menuItemNames);
		}

		// DATA
		{
			Set<String> menuItemNames = new HashSet<>();
			menuItemNames.add("miAmend");
			menuItemNames.add("miByte");
			menuItemNames.add("miShort");
			menuItemNames.add("miInt");
			menuItemNames.add("miDword");
			menuItemNames.add("miString");
			menuItemNames.add("miMin");
			menuItemNames.add("miMax");

			tableTagToMenuItem.put("DATA", menuItemNames);
		}

		// BYTE,SHORT,INT,DWORD
		{
			Set<String> menuItemNames = new HashSet<>();
			menuItemNames.add("miIf");
			menuItemNames.add("miFor");
			menuItemNames.add("miElseIf");
			menuItemNames.add("miMin");
			menuItemNames.add("miMax");
			menuItemNames.add("miDelTag");

			tableTagToMenuItem.put("BYTE", menuItemNames);
			tableTagToMenuItem.put("SHORT", menuItemNames);
			tableTagToMenuItem.put("INT", menuItemNames);
			tableTagToMenuItem.put("DWORD", menuItemNames);
		}

		// STRING
		{
			Set<String> menuItemNames = new HashSet<>();
			menuItemNames.add("miMin");
			menuItemNames.add("miMax");
			menuItemNames.add("miDelTag");

			tableTagToMenuItem.put("STRING", menuItemNames);
		}

		// IF
		{
			Set<String> menuItemNames = new HashSet<>();
			menuItemNames.add("miByte");
			menuItemNames.add("miShort");
			menuItemNames.add("miInt");
			menuItemNames.add("miDword");
			menuItemNames.add("miString");
			menuItemNames.add("miAmend");
			menuItemNames.add("miDelTag");

			tableTagToMenuItem.put("IF", menuItemNames);
		}
		
		// FOR,ELSEIF
		{
			Set<String> menuItemNames = new HashSet<>();
			menuItemNames.add("miByte");
			menuItemNames.add("miShort");
			menuItemNames.add("miInt");
			menuItemNames.add("miDword");
			menuItemNames.add("miString");
			menuItemNames.add("miDelTag");

			tableTagToMenuItem.put("FOR", menuItemNames);
			tableTagToMenuItem.put("ELSEIF", menuItemNames);
		}

		// MIN,MAX
		{
			Set<String> menuItemNames = new HashSet<>();
			menuItemNames.add("miAmend");
			menuItemNames.add("miDelTag");

			tableTagToMenuItem.put("MIN", menuItemNames);
			tableTagToMenuItem.put("MAX", menuItemNames);
		}
	}

	@FXML
	void OnMenuListAdd(ActionEvent event) {
		
	}
	
	@FXML
	void OnMenuListRemove(ActionEvent event) {
		
	}
	
	private void addTreeViewNode(String node) {
		TreeItem<String> selectedTreeItem = treeViewProtocol.getSelectionModel().getSelectedItem();
		if (null == selectedTreeItem) {
			Log.error("没有选中的节点.null == selectedTreeItem");
			return ;
		}
		
		if (!(selectedTreeItem instanceof NodeTreeItem)) {
			Log.error("!(selectedTreeItem instanceof NodeTreeItem)");
			return ;
		}
		
		NodeTreeItem nodeTreeItem = (NodeTreeItem) selectedTreeItem;

		switch (node) {
		case "BYTE":
		case "SHORT":
		case "INT":
		case "DWORD": 
		case "STRING": {
			Element newElement = nodeTreeItem.newElement(node);
			nodeTreeItem.createChildNode(newElement, nodeTreeItem);
			break;
		}
		case "IF": {
			// 判断子节点中没有IF
			TextInputDialog inputDialog = new TextInputDialog();
			inputDialog.setTitle("添加标签：IF");
			inputDialog.setHeaderText("输入整数类型！");
			inputDialog.setContentText("equals=");
			
			Optional<String> result = inputDialog.showAndWait();
			if (result.isPresent()) {
				Element newElement = nodeTreeItem.newElement(node);
				newElement.addAttribute("equals", result.get());
				nodeTreeItem.createChildNode(newElement, nodeTreeItem);
			}
			break;
		}
		case "ELSEIF": {
			if (!nodeTreeItem.hasChildNode(node)) {
				Element newElement = nodeTreeItem.newElement(node);
				nodeTreeItem.createChildNode(newElement, nodeTreeItem);
			} else {
				Utils.warningAlert("警告", "已经存在此节点：" + node, "当前节点下不能添加重复节点。");
			}
			break;
		}
		case "FOR": {
			if (!nodeTreeItem.hasChildNode(node)) {
				Element newElement = nodeTreeItem.newElement(node);
				nodeTreeItem.createChildNode(newElement, nodeTreeItem);
			} else {
				Utils.warningAlert("警告", "已经存在此节点：" + node, "当前节点下不能添加重复节点。");
			}
			break;
		}
		case "MIN":
		case "MAX": {
			if (!nodeTreeItem.hasChildNode(node)) {
				TextInputDialog inputDialog = new TextInputDialog();
				inputDialog.setTitle("添加标签：" + node);
				inputDialog.setHeaderText("输入整数类型！");
				inputDialog.setContentText(node + "=");
				
				inputDialog.showAndWait().ifPresent(value -> {
					Element newElement = nodeTreeItem.newElement(node);
					newElement.setText(value);
					nodeTreeItem.createChildNode(newElement, nodeTreeItem);
				});
			} else {
				Utils.warningAlert("警告", "已经存在此节点：" + node, "当前节点下不能添加重复节点。");
			}
			break;
		}
		default:
			Log.error("添加未知的节点：{}", node);
			break;
		}

	}
	
}

/**
 * @author hanzhe
 * 基类
 */
class TreeItemBase extends TreeItem<String> {
	protected final String nodeName;
	protected final Element element;
	protected final TreeItemBase parent;
	
	TreeItemBase(String nodeName, Element element, TreeItemBase parent) {
		this.nodeName = nodeName;
		this.element = element;
		this.parent = parent;
	}
	
	public void expandAll() {
		this.setExpanded(true);
		
		for (TreeItem<String> childTreeItem : getChildren()) {
			if (childTreeItem instanceof TreeItemBase) {
				TreeItemBase treeItemBase = (TreeItemBase)childTreeItem;
				treeItemBase.expandAll();
			}
		}
	}
	
	public String getNodeName() {
		return nodeName;
	}

	public Element getElement() {
		return element;
	}
}

class RootProtocolTreeItem extends TreeItemBase {
	
	RootProtocolTreeItem(Element elementRoot) {
		super("", elementRoot, null);
		
		this.setValue("root");
		
		showTree();
	}
	
	@SuppressWarnings("unchecked")
	public void showTree() {
		if (null == element) {
			Log.error("null == element.");
			return;
		}

		// 遍历类型数据
		Iterator<Element> it = element.elementIterator();
		while (it.hasNext()) {
			Element element = it.next();
			
			// 读取ID
			Iterator<Element> itID = element.elementIterator("ID");
			if (!itID.hasNext()) {
				Log.error("协议不存在ID标签。");
				continue;
			}
			Element elementID = itID.next();
			
			String strID = elementID.getStringValue();
			if (null == strID) {
				Log.error("协议ID标签无数据。");
				continue;
			}
			
			int nProtocolId = Integer.valueOf(strID);

			new ProtocolTreeItem(nProtocolId, element, this);
		}
	}

	public void addProtocol() {
		TextInputDialog inputDialog = new TextInputDialog();
		inputDialog.setTitle("添加协议：" + nodeName);
		inputDialog.setHeaderText("输入整数类型！");
		inputDialog.setContentText("ID=");
		
		inputDialog.showAndWait().ifPresent(value -> {
			int newProtocolId = Integer.valueOf(value);
			
			// 检查协议是否存在
//			for (TreeItem<String> treeItem : this.getChildren()) {
//				if (treeItem instanceof ProtocolTreeItem) {
//					ProtocolTreeItem protocolTreeItem = (ProtocolTreeItem)treeItem;
//					if (protocolTreeItem.getProtocolId() == newProtocolId) {
//						Utils.warningAlert("警告", "协议ID已经存在！", "请检查协议ID！");
//						return;
//					}
//				}
//			}
			
			Element elementProtocol = element.addElement("PROTOCOL");
			Element elementID = elementProtocol.addElement("ID");
			elementID.setText(value);
			Element elementDATA = elementProtocol.addElement("DATA");
			elementDATA.addAttribute("type", "simple");

			new ProtocolTreeItem(newProtocolId, elementProtocol, this);
		});
	}
	
	public void deleteProtocol(ProtocolTreeItem protocolTreeItem) {
		this.element.remove(protocolTreeItem.getElement());
		
		this.getChildren().remove(protocolTreeItem);
	}
}

class ProtocolTreeItem extends TreeItemBase {
	private int protocolId = 0;
	ProtocolTreeItem(int nProtocolId, Element element, TreeItemBase parent) {
		super("", element, parent);
		
		String strShowText = String.valueOf("协议Id:" + nProtocolId);
		super.setValue(strShowText);
		
		parent.getChildren().add(this);
//		parent.setExpanded(true);

		this.protocolId = nProtocolId;
	}
	
	public int getProtocolId() {
		return protocolId;
	}

	public Element getElement() {
		return element;
	}
	
	public void deleteSelf() {
		if (parent instanceof RootProtocolTreeItem) {
			RootProtocolTreeItem rootProtocolTreeItem = (RootProtocolTreeItem)parent;
			rootProtocolTreeItem.deleteProtocol(this);
		}
	}
}


class RootNodeTreeItem extends TreeItemBase {
	private final int protocolId;
	
	RootNodeTreeItem(int protocolId, Element element) {
		super("root", element, null);
		
		this.protocolId = protocolId;
		
		this.setValue(nodeName);
		
		showTree();
	}
	
	@SuppressWarnings("unchecked")
	public void showTree() {
		if (null == element) {
			Log.error("null == element.nProtocolId:{}", protocolId);
			return;
		}

		// 遍历类型数据
		Iterator<Element> itType = element.elementIterator();
		while (itType.hasNext()) {
			Element eleSub = itType.next();

			Log.debug("\ttype:{}", eleSub.getName());

			new NodeTreeItem(eleSub, this);
		}
	}
	
}

class NodeTreeItem extends TreeItemBase {
	
	NodeTreeItem(Element element, TreeItemBase parent) {
		super(element.getName(), element, parent);
		
		this.show();

		parent.getChildren().add(this);
//		parent.setExpanded(true);

		createChildren();
	}

	protected void show() {
		String strShowText = nodeName;
		if ("IF" == nodeName) {
			Attribute attrType = element.attribute("equals");
			if (null != attrType) {
				strShowText = nodeName + " equals = " + attrType.getValue();
			}
		} else if ("MIN" == nodeName) {
			strShowText = nodeName + " = " + element.getStringValue();
		} else if ("MAX" == nodeName) {
			strShowText = nodeName + " = " + element.getStringValue();
		} else if ("ID" == nodeName) {
			strShowText = nodeName + " = " + element.getStringValue();
		} else if ("DATA" == nodeName) {
			Attribute attrType = element.attribute("type");
			if (null != attrType) {
				strShowText = nodeName + " type = " + attrType.getValue();
			}
		}

		super.setValue(strShowText);
	}
	
	/**
	 * 修改数据
	 * @param value
	 */
	public void amendText() {
		if ("IF" == nodeName) {
			Attribute attribute = this.element.attribute("equals");
			if (null == attribute) {
				Log.error("null == attribute.nodeName:{}", this.nodeName);
				return ;
			}
			
			TextInputDialog inputDialog = new TextInputDialog(attribute.getValue());
			inputDialog.setTitle("修改：" + nodeName);
			inputDialog.setHeaderText("输入整数类型！");
			inputDialog.setContentText("equals=");
			
			inputDialog.showAndWait().ifPresent(value -> {
				attribute.setText(value);
			});
		} else if ("MIN" == nodeName || "MAX" == nodeName || "ID" == nodeName) {
			TextInputDialog inputDialog = new TextInputDialog(this.element.getText());
			inputDialog.setTitle("修改：" + nodeName);
			inputDialog.setHeaderText("输入整数类型！");
			inputDialog.setContentText(nodeName + "=");
			
			inputDialog.showAndWait().ifPresent(value -> {
				this.element.setText(value);
			});
		} else if ("DATA" == nodeName) {
			List<String> choices = new ArrayList<>();
			choices.add("simple");
			choices.add("ignore");
			choices.add("onlylength");
			
			ChoiceDialog<String> choiceDialog = new ChoiceDialog<>("simple", choices);

			choiceDialog.showAndWait().ifPresent(value -> {
				Attribute attribute = this.element.attribute("type");
				if (null == attribute) {
					this.element.addAttribute("type", value);
				} else {
					attribute.setText(value);
				}
			});
		}
		
		show();
	}

	@SuppressWarnings("unchecked")
	public void createChildren() {
		if (null == element) {
			Log.error("null == element.");
			return;
		}

		// 遍历类型数据
		Iterator<Element> itType = element.elementIterator();
		while (itType.hasNext()) {
			Element eleSub = itType.next();

			Log.debug("\ttype:{}", eleSub.getName());

			new NodeTreeItem(eleSub, this);
		}
	}
	
	/**
	 * 存在nodeName相同的子节点
	 * @param nodeName
	 * @return
	 */
	public boolean hasChildNode(String nodeName) {
		// 判断子节点中没有IF
		for (TreeItem<String> treeItem : this.getChildren()) {
			if (treeItem instanceof NodeTreeItem) {
				NodeTreeItem childNode = (NodeTreeItem)treeItem;
				if (childNode.getNodeName().equals(nodeName)) {
					return true;
				}
			}
		}
		
		return false;
	}
	
	/**
	 * 添加子节点
	 * @param nodeName
	 * @return
	 */
	public Element newElement(String nodeName) {
		return element.addElement(nodeName);
	}
	
	/**
	 * 创建子节点显示
	 * @param childElement
	 * @param detailTreeItem
	 */
	public void createChildNode(Element childElement, TreeItem<String> detailTreeItem) {
		if (null == childElement) {
			Log.error("null == childElement");
			return ;
		}
		
		new NodeTreeItem(childElement, this);
		
		this.setExpanded(true);
	}
	
	public void removeSelf() {
		if (null == parent) {
			Log.error("null == parent.nodeName:{}", this.nodeName);
			return ;
		}
		
		if (parent instanceof NodeTreeItem) {
			NodeTreeItem nodeTreeItem = (NodeTreeItem)parent;
			
			nodeTreeItem.removeChildNode(this);
		}
	}
	
	protected void removeChildNode(NodeTreeItem childNode) {
		this.element.remove(childNode.element);
		
		this.getChildren().remove(childNode);
	}

}
